import JSONAPISerializer from "json-api-serializer"
import request from "../../utils/request";
import flarum from "../../flarum";
import {urlEncode} from "../../utils/tools";

export class Tags {
    constructor() {
        this.serializer = new JSONAPISerializer()
        this.serializer.register("tags", {
            id: "id",
            relationships: {
                discussions: {
                    type: "discussions"
                }
            }
        })

        this.serializer.register('discussions', {
            id: "id"
        })
    }

    /**
     * 获取API地址
     * @returns {string}
     */
    getApi(include = "children,lastPostedDiscussion,parent") {
        return `${flarum.api}/tags?include=` + urlEncode(include)
    }

    /**
     * 执行请求
     * @param func
     */
    execute(func) {
        const that = this
        request.get(that.getApi()).then(res => {
            that.data = res
            that.viewdata = that.serializer.deserialize("tags", res)
            func(that.data, that.viewdata)
        }).catch(res => {})
    }
}